package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @autahor: csl
 * @date: 2019/7/26
 * @description:
 * @version:1.0
 */
public class securityUserDetailsService implements UserDetailsService{
    @Reference
    private UserService service;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.itheima.health.pojo.User currUser = service.findByUsername(s);
        if (currUser==null){
            System.out.println("用户不存在");
            return null;
        }
        List<GrantedAuthority>grantedAuthorityList=new ArrayList<>();
       for (Role role:currUser.getRoles()){
           grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
           for (Permission permission:role.getPermissions()){
               grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
           }
       }
        String password = currUser.getPassword();
        UserDetails userDetails = new User(s,password,grantedAuthorityList);
        System.out.println("================");
        return userDetails;
    }
}
